import os
import pandas as pd
import math

class utils:
    # 将文读取为矩阵，暂定仅支持读取excel
    def read_data(file_path):
        print(f'读取文件路径为:{file_path}')
        df = pd.read_excel(file_path)
        return df
    
    # 对矩阵进行切分
    def df_split(df, *idxs):
        for idx in idxs:
            df = df.iloc[idx[0]:idx[1], idx[2]:idx[3]]
        return df
    
    # 计算数据集的信息熵
    def calc_entropy(df, col):
        # matrix = df.values.tolist()
        # 对全部分类进行统计
        results = df.groupby(col)
        comentropy = 0.0
        # 获取全部信息计数
        total_count = df.values.size
        for result in results:
            # 获取当前分类计数
            cur_count = result[1].values.size
            # 计算当前分类概率
            probability = cur_count/(total_count * 1.0)
            # 计算信息熵
            comentropy += -(probability * math.log2(probability))
        return comentropy
    
    # 计算条件信息熵
    def calc_cond_entropy(df, classify_col, result_col):
        # 按照指定的分类对数据集进行分组
        data_groups = df.groupby(classify_col)
        # 对每个分类计算条件信息熵
        df_count = df.values.size * 1.0
        cond_entropy = 0.0
        for data_group in data_groups:
            cur_df_count = data_group[1].values.size
            cond_entropy += cur_df_count / df_count * utils.calc_entropy(cur_df_count, 'Play')
    
    # 计算信息增益率